package com.zjtaixue.usersite.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zjtaixue.usersite.domain.College;
import com.zjtaixue.usersite.domain.Login;
import com.zjtaixue.usersite.domain.Teacher;
import com.zjtaixue.usersite.exception.ApplicationException;
import com.zjtaixue.usersite.mapper.CollegeMapper;
import com.zjtaixue.usersite.mapper.LoginMapper;
import com.zjtaixue.usersite.mapper.TeacherMapper;
import com.zjtaixue.usersite.page.PageResult;
import com.zjtaixue.usersite.query.TeacherQueryObject;
import com.zjtaixue.usersite.service.TeacherService;
import com.zjtaixue.usersite.util.MD5Util;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import static com.zjtaixue.usersite.domain.Login.STATE_ENABLE;
import static com.zjtaixue.usersite.domain.Login.TYPE_TEACHER;

@Service("teacherService")
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private LoginMapper loginMapper;

    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;

    //获取总行数
    public int getTotalRows() {
        return totalRows;
    }

    //获取总列数
    public int getTotalCells() {
        return totalCells;
    }

    @Override
    public PageResult<JSONObject> listPageResult(TeacherQueryObject qo) {
        int count = teacherMapper.queryCount(qo);
        if (count > 0) {
            List<Teacher> teachers = teacherMapper.query(qo);
            List<JSONObject> jsonObjects = new ArrayList<>();
            for (Teacher teacher : teachers) {
                JSONObject jsonObject = (JSONObject) JSON.toJSON(teacher);
                jsonObject.put("college", collegeMapper.selectByPrimaryKey(teacher.getCollegeId()));
                List<Login> logins = loginMapper.listByUserInfoId(teacher.getId(), (byte) 1);
                if (logins != null && logins.size() > 0) {
                    jsonObject.put("state", logins.get(0).getState());
                }
                jsonObjects.add(jsonObject);
            }
            return new PageResult(jsonObjects, qo.getCurrentPage(), count, qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }

    @Override
    public void insert(Teacher teacher) {
        int count = teacherMapper.countByNumber(teacher.getNumber());
        if (count > 0) {
            throw new ApplicationException("已存在相同工号的教师！");
        }
        teacherMapper.insert(teacher);
        Login login = new Login();
        login.setUserinfoId(teacher.getId());
        login.setState(STATE_ENABLE);
        login.setUsername(teacher.getNumber());
        login.setPassword(MD5Util.encode("123456"));
        login.setType(TYPE_TEACHER);
        loginMapper.insert(login);
    }

    @Override
    public int deleteById(Integer id) {
        loginMapper.deleteByUserInfoAndType(id, TYPE_TEACHER);
        return teacherMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Teacher teacher) {
        int count = teacherMapper.countOthersByNumber(teacher);
        if (count > 0) {
            throw new ApplicationException("已存在相同工号的教师");
        }
        Login login = loginMapper.findByUserInfoAndType(teacher.getId(), TYPE_TEACHER);
        login.setUsername(teacher.getNumber());
        loginMapper.updateByPrimaryKey(login);
        teacherMapper.updateByPrimaryKey(teacher);
    }

    @Override
    public Teacher getById(Integer id) {
        return teacherMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Teacher> gainInfo(InputStream is) {
        List<Teacher> teachers = new ArrayList<Teacher>();
        Workbook wb = null;
        try {
            wb = new XSSFWorkbook(is);
            teachers = readValue(wb);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ApplicationException(e.toString());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new ApplicationException(e.toString());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        return teachers;
    }

    @Override
    public List<Teacher> readValue(Workbook wb) throws ParseException {
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        //得到Excel的行数
        this.totalRows = sheet.getLastRowNum() + 1;
        //得到Excel的列数(前提是有行数)
        if (totalRows >= 1 && sheet.getRow(0) != null) {//判断行数大于一，并且第一行必须有标题（这里有bug若文件第一行没值就完了）
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        } else {
            throw new ApplicationException("Excel表格格式不正确,请下载模板进行更改");
        }
        List<Teacher> teachers = new ArrayList<Teacher>();//声明一个对象集合
        Login login = new Login();
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            //循环Excel的列
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                switch (c) {
                    case 0://学院
                        if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                            throw new ApplicationException("请您在Excel表中填入学院名称!" + "\t(第" + (r + 1) + "行，" + "第" + (c + 1) + "列)");
                        }
                        break;
                    case 1://教师姓名
                        if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                            throw new ApplicationException("请您在Excel表中填入教师姓名!" + "\t(第" + (r + 1) + "行，" + "第" + (c + 1) + "列)");
                        }
                        break;
                    case 2://工号
                        if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
                            throw new ApplicationException("请您在Excel表中填入工号!" + "\t(第" + (r + 1) + "行，" + "第" + (c + 1) + "列)");
                        }
                        break;
                }
            }
        }
        //循环Excel行数,从第二行开始。标题不入库
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;
            //循环Excel的列
            Integer collegeId = 0;
            String teacherNumber = "", teacherName = "";
            for (int c = 0; c < this.totalCells; c++) {
                Cell cell = row.getCell(c);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                switch (c) {
                    case 0:
                        //获取学院信息
                        College college = collegeMapper.selectByCollegeName(cell.getStringCellValue().trim());
                        if (college == null) {
                            //学院信息为空，则添加学院信息
                            college = new College();
                            college.setName(cell.getStringCellValue().trim());
                            collegeMapper.insert(college);
                        }
                        collegeId = college.getId();
                        break;
                    case 1:
                        teacherName = cell.getStringCellValue().trim();
                        break;
                    case 2:
                        teacherNumber = cell.getStringCellValue().trim();
                        break;
                }
            }
            Integer result = teacherMapper.countByNumber(teacherNumber);
            if (result == 0) {
                Teacher teacher = new Teacher();
                teacher.setCollegeId(collegeId);
                teacher.setName(teacherName);
                teacher.setNumber(teacherNumber);
                teacherMapper.insert(teacher);
                //添加登入信息
                login.setUsername(teacher.getNumber());
                login.setPassword(MD5Util.encode("123456"));
                login.setState(STATE_ENABLE);
                login.setType(TYPE_TEACHER);
                login.setUserinfoId(teacher.getId());
                loginMapper.insert(login);
                //添加对象到集合中
                teachers.add(teacher);
            } else {
                throw new ApplicationException("Excel中教师工号重复!" + "\t(第" + (r + 1) + "行，" + "第" + 6 + "列)\r\n" +
                        "重复的工号是:" + teacherNumber);
            }

        }
        return teachers;
    }

    @Override
    public int disabledById(Integer id) {
        List<Login> logins = loginMapper.listByUserInfoId(id, (byte) 1);
        if (logins != null && logins.size() > 0) {
            return loginMapper.disable(logins.get(0).getId());
        }
        return 0;
    }

    @Override
    public int enableById(Integer id) {
        List<Login> logins = loginMapper.listByUserInfoId(id, (byte) 1);
        if (logins != null && logins.size() > 0) {
            return loginMapper.enable(logins.get(0).getId());
        }
        return 0;
    }
}
